<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Session;
use think\Cache;

class Common extends Controller
{
    /**
     * 基础控制器初始化
     * @author 苏晓信
     */
    public function _initialize()
    {
        //Session::delete('userId');
        //是否已登陆
        $userId = Session::get('userId');
        $userId = 16;//测试用户ID

        //是否存在
        if($userId){
            $user = Db::table('tf_front_user')->where('id',$userId)->field('id')->find();
            if(!$user){
                //获取微信登录授权
                $this->wxLogin();
            }else{
                Session::set('userId',$user['id']);
            }
        }else{
            //获取微信登录授权
            $this->wxLogin();
        }


        define('MODULE_NAME', request()->module());
        define('CONTROLLER_NAME', request()->controller());
        define('ACTION_NAME', request()->action());
        
        $box_is_pjax = $this->request->isPjax();
        $this->assign('box_is_pjax', $box_is_pjax);
    }

    //微信登陆
    public function wxLogin(){

        $code = input('code');
        $cacheCode = Cache::get('code');
        if($code){

            //限制微信重定向两次BUG
            if ($cacheCode == $code) {
                exit;
            }

            Cache::set('code', $code, 3600);

            //已获取code码，获取openid
            $openidData = $this->getOpenidFromMp($code);


            //获取用户详情
            $wxUserInfo = $this->getWxUserInfo($openidData);
            //保存用户信息

            //是否存在
            $is_exist = Db::table('tf_front_user')->where('open_id',$wxUserInfo->openid)->find();

            if(!$is_exist){
                $data = [
                    'open_id'=>$wxUserInfo->openid,
                    'wxname'=>$wxUserInfo->nickname,
                    'sex'=>$wxUserInfo->sex,
                    'user_img'=>$wxUserInfo->headimgurl,
                    'addr'=> $wxUserInfo->country. $wxUserInfo->province . $wxUserInfo->city,
                    'create_time'=> time(),
                ];
                Db::table('tf_front_user')->insert($data);
                $userId = Db::table('tf_front_user')->getLastInsID();
                Session::set('userId',$userId);
            }else{
                Session::set('userId',$is_exist['id']);
            }
        }else{
            //触发微信返回code码
            $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
            $url = $this->__CreateOauthUrlForCode($baseUrl);
            Header("Location: $url");
            exit();
        }
    }

    //获取微信用户详情
    public function getWxUserInfo($openidData){
        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$openidData['access_token'].'&openid='.$openidData['openid'].'&lang=zh_CN';
        return json_decode(file_get_contents($user_info_url));
    }


    /**
     *
     * 构造获取code的url连接
     * @param string $redirectUrl 微信服务器回跳的url，需要url编码
     *
     * @return 返回构造好的url
     */
    private function __CreateOauthUrlForCode($redirectUrl)
    {
        $urlObj["appid"] = config('wxconfig')['appID'];
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_userinfo";
        $urlObj["state"] = "STATE"."#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }

    /**
     *
     * 拼接签名字符串
     * @param array $urlObj
     *
     * @return 返回已经拼接好的字符串
     */
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    /**
     *
     * 通过code从工作平台获取openid机器access_token
     * @param string $code 微信跳转回来带上的code
     *
     * @return openid
     */
    public function GetOpenidFromMp($code)
    {
        $url = $this->__CreateOauthUrlForOpenid($code);
        //初始化curl
        $ch = curl_init();
        //设置超时
        // curl_setopt($ch, CURLOPT_TIMEOUT, $this->curl_timeout);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //运行curl，结果以jason形式返回
        $res = curl_exec($ch);
        curl_close($ch);
        //取出openid
        $data = json_decode($res,true);
        // 结果检测
        if(empty($data['openid'])) {
            dump($data);exit;
        }
        return $data;
    }


    /**
     *
     * 构造获取open和access_toke的url地址
     * @param string $code，微信跳转带回的code
     *
     * @return 请求的url
     */
    private function __CreateOauthUrlForOpenid($code)
    {
        $urlObj["appid"] = config('wxconfig')['appID'];
        $urlObj["secret"] = config('wxconfig')['appsecret'];
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
    }
}